package com.mjh.config;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.errors.*;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @author MJH
 * @date 2021-12-15
 * @Description minio文件服务配置
 */

@Configuration
public class MInioConfig {

    @Value("${minio.host}")
    public String MINIO_HOST;

    @Value("${minio.root.user}")
    public String MINIO_ROOT_USER;

    @Value("${minio.root.password}")
    public String MINIO_ROOT_PASSWORD;

    @Value("${minio.bucket}")
    public String bucket;


    @Bean
    public MinioClient minioClient(){

        MinioClient client=
                MinioClient.builder()
                .endpoint(MINIO_HOST)
                .credentials(MINIO_ROOT_USER,MINIO_ROOT_PASSWORD)
                .build();

       //判断存储桶是否存在
        boolean flag = false;
        try {
            flag = client.bucketExists(BucketExistsArgs.builder().bucket(bucket).build());
            if (!flag){
                //创建存储桶
               client.makeBucket(MakeBucketArgs.builder().bucket(bucket).build());
            }
        } catch (ErrorResponseException e) {
            e.printStackTrace();
        } catch (InsufficientDataException e) {
            e.printStackTrace();
        } catch (InternalException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (InvalidResponseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (XmlParserException e) {
            e.printStackTrace();
        }

        return  client;
    }
}
